<?php
namespace App\Service\Order;

use DB;

use App\Models\Tg\TgBill;

use App\Service\WdhService;

use App\Models\Goods\GoodsStore;

use Illuminate\Support\Facades\Redis as Redis;

class TgOrderService extends OrderService
{

    public function __construct($bill, $creator = 'system')
    {
        parent::__construct($bill, $creator);
    }


    /**
     * 生成团购待保存数据
     * @return bool
     */
    private function createTgOrder()
    {

        //保存团购订单信息
        $tg_bill = new TgBill();
        $tg_bill->uuid = makeUuid();
        $tg_bill->timeStamp = $this->datetime;
        $tg_bill->creator = $this->creator;
        $tg_bill->createTime = $this->datetime;
        $tg_bill->bill_no = $this->bill_no;
        $tg_bill->payTypeID = $this->bill['payTypeID'];
        $tg_bill->payTypeName = $this->bill['payTypeName'];
        $tg_bill->pay_code = '0';
        $tg_bill->pay_status = $this->pay_status;
        $this->insert['tg_bill'][] = $tg_bill;
        
        return true;
        
    }

    public function submit()
    {
        //获取主团订单号
        if (!$this->bill['parent_bill_no']) {
            $this->bill['parent_bill_no'] = $this->bill_no;
        }

        $this->createTgOrder();

        $this->createGoods();

        $this->createPay();

        $this->createTrace();

        $this->createMaster();

        try {

            DB::beginTransaction();

            foreach ($this->insert as &$table) {

                foreach ($table as &$model) {

                    $model->save();

                    if ($model['table'] == 'bill_pay') {
                        if ($model->payTypeID == 2) { //余额
                            $balance_data = array(
                                'cardNo' => $this->cardNo,
                                'pcustID' => $this->pcustID,
                                'custID' => $this->custID,
                                'openId' => $this->openId,
                                'amount' => $model->pay_amount,
                                'password' => $this->bill['payPwd'],
                                'remark' => '订单' . $this->bill_no . '使用余额'
                            );
                            $res = WdhService::deductionBalance($balance_data);
                            if ($res['code'] != 200) {
                                throw new \Exception($res['message'], 400);
                            }
                        } elseif ($model->payTypeID == 3) { //积分
                            $points_data = array(
                                'cardNo' => $this->cardNo,
                                'pcustID' => $this->pcustID,
                                'custID' => $this->custID,
                                'openId' => $this->openId,
                                'points' => $model->pay_amount,
                                'remark' => '订单' . $this->bill_no . '使用积分'
                            );
                            $res = WdhService::deductionPoints($points_data);
                            if ($res['code'] != 200) {
                                throw new \Exception($res['message'], 400);
                            }
                        }
                    } else if ($model['table'] == 'bill_goods') {

                        //扣减库存
                        $store_row = GoodsStore::where([
                            ['storeID', '=', $this->bill['mallID']],
                            ['product_code', '=', $model->product_code],
                            ['enableSaleAmount', '>=', $model->goods_amount],
                        ])->decrement('enableSaleAmount', $model->goods_amount);
                        if (!$store_row) {
                            throw new \Exception('商品:' . $model->goods_name . '库存不足，下单失败', 400);
                        }

                        //检查团购库存并扣减
                        $goods_buy_count = Redis::incrBy('TG_GOODS_BUY_NUM_' . $this->bill['tuan_id'] . '_' . $model->goods_postID, $model->goods_amount);
                        if ($goods_buy_count > $this->bill['tuan_store']) {
                            Redis::decrBy('TG_GOODS_BUY_NUM_' . $this->bill['tuan_id'] . '_' . $model->goods_postID, $model->goods_amount);
                            throw new \Exception('团购商品:' . $model->goods_name . '库存不足，下单失败', 400);
                        }

                    }

                }

            }

            DB::commit();

            //增加团购购买数
            Redis::incrBy('TG_BUY_NUM_' . $this->bill['tuan_id'], $this->bill['goods'][0]['goods_amount']);

            //更新会员手机，名称
            if( isset($this->bill['deliver_mobile'] , $this->bill['deliver_name']) && isMobile($this->bill['deliver_mobile']) && !empty($this->bill['deliver_name']) ){
                $deliver_data = array(
                    'cust_mobile' => $this->bill['deliver_mobile'],
                    'cust_name' => $this->bill['deliver_name']
                );
                Redis::setex('CUST_ZITI_INFO_' .  $this->pcustID, 630720000, json_encode($deliver_data, true));
            }

            //订单号保存到redis中
            Redis::sAdd('TG_UNPAID_' . $this->bill['tuan_id'] , $this->bill_no);

            //保存会员正在参团，或开团信息
            $redis_json = json_encode([
                'bill_no' => $this->bill_no,
                'parent_bill_no' => $this->bill['parent_bill_no'],
                'bill_status' => 0,
                'pay_status' => $this->pay_status
            ],true);
            Redis::set('G_WDH_CUSTOMER_TG_' . $this->bill['tuan_id'] . '_' . $this->pcustID, $redis_json);

            if ( $this->bill['tuan_type'] == 1 && $this->bill['bill_payable'] == 0 ) {
                //消息推送
                WdhService::ptOrderPay(array('bill_no' => $this->bill_no));
            }

            $return_data = [
                'mallID' => $this->bill['mallID'],
                'pcustID' => $this->pcustID,
                'mallCode' => $this->bill['mallCode'],
                'bill_no' => $this->bill_no,
                'parent_bill_no' => $this->bill['parent_bill_no'],
                'pay_amount' => $this->bill['bill_payable'],
                'pay_status' => $this->pay_status,
                'openId' => $this->bill['openId']
            ];

            return array('code' => 200, 'message' => '团购单保存成功', 'data' => $return_data);

        } catch (\Exception $e) {
            DB::rollBack();

            if ($e->getCode() > 0) {
                return array('code' => $e->getCode(), 'message' => $e->getMessage());
            } else {
                return array('code' => 500, 'message' => '系统错误');
            }
        }

    }

}